package api

import (
	"api-gateway/basic/consts"
	__ "api-gateway/basic/proto"
	"api-gateway/handler/request"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	jwt2 "github.com/golangblogs/gojwt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"net/http"
	"time"
)

func SendSms(c *gin.Context) {
	var req request.SendSmsReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"data": nil,
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	c1 := __.NewSrvClient(conn)
	sms, _ := c1.SendSms(c, &__.SendSmsRequest{
		Mobile: req.Mobile,
		Source: req.Source,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"data": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"data": map[string]interface{}{
			"SendSms": sms,
		},
	})

}

func Login(c *gin.Context) {
	var req request.LoginReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"data": nil,
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	c1 := __.NewSrvClient(conn)
	sms, _ := c1.Login(c, &__.LoginRequest{
		Mobile:  req.Mobile,
		SendSms: req.SendSms,
	})
	j := jwt2.NewJWT(consts.KEY_SECRET_JWT)
	claims := jwt2.CustomClaims{
		ID: uint(sms.Id),

		StandardClaims: jwt.StandardClaims{ExpiresAt: time.Now().UnixNano() * 3600},
	}
	token, _ := j.CreateToken(claims)

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"data": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"data": map[string]interface{}{
			"user":  sms,
			"token": token,
		},
	})
}

func HomePage(c *gin.Context) {
	var req request.HomePageReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"data": nil,
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	c1 := __.NewSrvClient(conn)
	sms, _ := c1.HomePage(c, &__.HomePagRequest{
		UserId: int64(c.GetUint("userId")),
	})
	fmt.Println(req.UserId)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"data": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"data": map[string]interface{}{
			"home": sms,
		},
	})
}
